package com.adlotto2.lcdns.util;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Process;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import com.adlotto2.lcdns.R;
import com.adlotto2.lcdns.cronos.asynctask.CNDataAsyncTask;

public class ApplicationUtils {
	
	/** 카카오톡 메시지 정보 */
	public static String strMessage = "인생역전어플~!";  
	public static String strURL = "http://link.kakao.com";
	public static String strAppId = "com.kakao.android.image";
	public static String strAppVer = "2.0";
	public static String strAppName = "AD Lotto";
	public static String strInstallUrl = "market://details?id=com.adlotto2.lcdns"; 
	
	public static String getPhoneNumber(final Context context){
		String phoneNum = null;
		try{
			@SuppressWarnings("static-access")
			TelephonyManager telManager = (TelephonyManager)context.getSystemService(context.TELEPHONY_SERVICE); 
			phoneNum = telManager.getLine1Number();
			
			if(phoneNum.startsWith("+82"))
				phoneNum = phoneNum.replace("+82", "0");
			else if(phoneNum.startsWith("82"))
				phoneNum = phoneNum.replaceFirst("82", "0");
			
			CNCronosLog.d("getPhoneNumber","phoneNum1 : " + phoneNum);
		} catch(Exception e) {
			ApplicationUtils.showOkDialog(context, 0, context.getString(R.string.popup_alert), "USIM칩을 넣어주세요\n(USIM을 지원하지 앟는 단말에서는 서비스가 되지 않습니다.)", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					((Activity)context).finish();
					Process.killProcess(0);
				}
			});
			
			return null;
		}
		return phoneNum;
	}
	
	/**
	 * 확인 다이얼로그창 보여주기
	 */
	public static void showOkDialog(Context context, int icon, String title, String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setCancelable(false);
    	builder.setIcon(icon);
    	builder.setTitle(title);
    	builder.setMessage(message);

    	builder.setInverseBackgroundForced(true);
    	builder.setPositiveButton(context.getResources().getString(R.string.commons_ok), new DialogInterface.OnClickListener() {
    		@Override
    		public void onClick(DialogInterface dialog, int which) {
    			dialog.dismiss();
    		}
    	});
    	AlertDialog alert = builder.create();
    	alert.show();
	}
	
	/**
	 * 확인 다이얼로그창 보여주기 / 확인 버튼 기능 설정 가능
	 */
	public static void showOkDialog(Context context, int icon, String title, String message, DialogInterface.OnClickListener okClickListener) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setCancelable(false);
    	builder.setIcon(icon);
    	builder.setTitle(title);
    	builder.setMessage(message);

    	builder.setInverseBackgroundForced(true);
    	builder.setPositiveButton(context.getResources().getString(R.string.commons_ok), okClickListener);
    	AlertDialog alert = builder.create();
    	alert.show();
	}
	
	/**
	 * 확인, 취소 다이얼로그 창 보여주기
	 */
	public static void showOkCancelDialog(final Context context, int icon, String title, String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setCancelable(false);
    	builder.setIcon(icon);
    	builder.setTitle(title);
    	builder.setMessage(message);

    	builder.setInverseBackgroundForced(true);
    	builder.setPositiveButton(context.getResources().getString(R.string.commons_ok), new DialogInterface.OnClickListener() {
    		@Override
    		public void onClick(DialogInterface dialog, int which) {
    			dialog.dismiss();
    			((Activity)context).finish();
    		}
    	}); 
    	builder.setNegativeButton(context.getResources().getString(R.string.commons_cancel), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
    	AlertDialog alert = builder.create();
    	alert.show();
	}
	
	/**
	 * 확인, 취소 다이얼로그 창 보여주기 / 확인 버튼 기능 설정 가능
	 */
	public static void showOkCancelDialog(final Context context, int icon, String title, String message, DialogInterface.OnClickListener okClickListener) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setCancelable(false);
    	builder.setIcon(icon);
    	builder.setTitle(title);
    	builder.setMessage(message);

    	builder.setInverseBackgroundForced(true);
    	builder.setPositiveButton(context.getResources().getString(R.string.commons_ok), okClickListener); 
    	builder.setNegativeButton(context.getResources().getString(R.string.commons_cancel), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
    	AlertDialog alert = builder.create();
    	alert.show();
	}
	
	public static String makeStringWithComma(String string, boolean ignoreZero) {
		if (string.length() == 0) {
			return "";
		}
		try {
			if (string.indexOf(".") >= 0) {
				double value = Double.parseDouble(string);
				if (ignoreZero && value == 0) {
					return "";
				}
				DecimalFormat format = new DecimalFormat("###,##0.00");
				return format.format(value);
			} else {
				long value = Long.parseLong(string);
				if (ignoreZero && value == 0) {
					return "";
				}
				DecimalFormat format = new DecimalFormat("###,###");
				return format.format(value);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return string;
	}
	
	/**
	 * SharedPreferences String 값 세팅
	 * @param context
	 * @param key : String
	 * @param value
	 */
	public static void setStrPreferences(Context context, String key, String value)
	{
	    SharedPreferences pref = null;
	    
	    pref = context.getSharedPreferences(LottoAdConstants.PREFERENCE_NAME, Activity.MODE_PRIVATE);
	    SharedPreferences.Editor prefEditor = pref.edit();
	    prefEditor.putString(key, value);
	    
	    prefEditor.commit();
	}

	/**
	 * SharedPreferences String 값 가져오기  
	 * @param context
	 * @param key : String
	 * @return
	 */
	public static String getStrPreferences(Context context, String key)
	{
	    String returnValue = null;
	    
	    SharedPreferences pref = null;
	    pref = context.getSharedPreferences(LottoAdConstants.PREFERENCE_NAME, Activity.MODE_PRIVATE);
	    returnValue = pref.getString(key, "");
	    
	    return returnValue;
	}
	
	/**
	 * SharedPreferences Boolean 값 세팅
	 * @param context
	 * @param key : String
	 * @param value
	 */
	public static void setBoolPreferences(Context context, String key, boolean value)
	{
	    SharedPreferences pref = null;
	    
	    pref = context.getSharedPreferences(LottoAdConstants.PREFERENCE_NAME, Activity.MODE_PRIVATE);
	    SharedPreferences.Editor prefEditor = pref.edit();
	    prefEditor.putBoolean(key, value);
	    
	    prefEditor.commit();
	}
	
	/**
	 * SharedPreferences Boolean 값 가져오기  
	 * @param context
	 * @param key : String
	 * @return boolean
	 */
	public static boolean getBoolPreferences(Context context, String key)
	{
		boolean returnValue = false;
	    
	    SharedPreferences pref = null;
	    pref = context.getSharedPreferences(LottoAdConstants.PREFERENCE_NAME, Activity.MODE_PRIVATE);
	    returnValue = pref.getBoolean(key, false);
	    
	    return returnValue;
	}
	
	/**
	 * SharedPreferences Boolean 값 가져오기, 기본값 false;  
	 * @param context
	 * @param key : String
	 * @param bool : boolean
	 * @return
	 */
	public static boolean getBoolPreferences(Context context, String key, boolean bool)
	{
		boolean returnValue = false;
	    
	    SharedPreferences pref = null;
	    pref = context.getSharedPreferences(LottoAdConstants.PREFERENCE_NAME, Activity.MODE_PRIVATE);
	    returnValue = pref.getBoolean(key, bool);
	    
	    return returnValue;
	}
	
	/**
	 * SharedPreferences int 값 세팅
	 * @param context
	 * @param key : int
	 * @param value
	 */
	public static void setIntPreferences(Context context, String key, int value)
	{
	    SharedPreferences pref = null;
	    
	    pref = context.getSharedPreferences(LottoAdConstants.PREFERENCE_NAME, Activity.MODE_PRIVATE);
	    SharedPreferences.Editor prefEditor = pref.edit();
	    prefEditor.putInt(key, value);
	    
	    prefEditor.commit();
	}

	/**
	 * SharedPreferences int 값 가져오기  
	 * @param context
	 * @param key : int
	 * @return
	 */
	public static int getIntPreferences(Context context, String key)
	{
	    int returnValue = 0;
	    
	    SharedPreferences pref = null;
	    pref = context.getSharedPreferences(LottoAdConstants.PREFERENCE_NAME, Activity.MODE_PRIVATE);
	    returnValue = pref.getInt(key, 0);
	    
	    return returnValue;
	}
	
	/**
	 * errorNumber에 대한 에러 메세지 조회  
	 */
	public static String getErrorMessage(Context context, int errorNumber) {
		int messageId = 0;

		if (errorNumber != 0) {
			switch (errorNumber) {
			case CNDataAsyncTask.ERROR_CODE_FAIL: 					// 가져온 데이터에 오류가 있습니다(XML 에러)
				messageId = R.string.error_data_has_problem;
				break;
			case CNDataAsyncTask.ERROR_CODE_CALCEL: 				// 데이터 요청이 취소되었습니다.(사용자 취소)
				messageId = R.string.error_user_cancel;
				break;
			case CNDataAsyncTask.ERROR_CODE_NO_CONNECTION: 			// 네트워크에 연결할 수 없어 데이터를 가져올 수 없습니다.\n3G 또는 Wi-Fi를 켜주세요.
				messageId = R.string.error_failed_connect_network;
				break;
			case CNDataAsyncTask.ERROR_CODE_BAD_REQUEST: 			// 잘못된 요청입니다.(잘못된 요청,파라미터 누락이나 기타 등등...)
				messageId = R.string.error_badrequest;
				break;
			case CNDataAsyncTask.ERROR_CODE_SERVERERROR: 			// 서버에 연결 할 수 없어 데이터를 가져올 수 없습니다.\n잠시 후 다시 이용해 주시기 바랍니다.(서버 오류)
				messageId = R.string.error_failed_connect_server;
				break;
			case CNDataAsyncTask.ERROR_CODE_BREAK:					// 죄송합니다. 정기 점검 중입니다. 잠시 후 이용해주세요.(점검중)
				messageId = R.string.error_server_checking;
				break;
			default:
				messageId = R.string.error_unknown;					//서비스 오류 입니다. 잠시 후 다시 이용해 주시기 바랍니다.
				break;
			}
		}
		return context.getResources().getString(messageId);
	}
	
	public static void unbindDrawables(View view) {
        if (view.getBackground() != null) { 
        view.getBackground().setCallback(null); 
        } 
        if (view instanceof ViewGroup) { 
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { 
            unbindDrawables(((ViewGroup) view).getChildAt(i)); 
            }
	         
	        try {
	        	((ViewGroup) view).removeAllViews();
			} catch (Exception ignore) { // AdapterViews, ListViews and potentially
											// other ViewGroups don't support the
											// removeAllViews operation } }
			}
        } 
    }
	
	/**
     * 해당 패키지 존재 유,무 파악
     * @param context
     * @param package_name : 패키지 명
     */
	public static void checkPackage(Context context, final String package_name) {
		final PackageManager pm = context.getPackageManager();
		List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);

		Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + package_name));
		for (ApplicationInfo appInfo : packages) {
			if (package_name.equals(appInfo.packageName)) {
				goKaKao(context);
				return;
			}
		}
		context.startActivity(intent);
	}
    
    /**
     * 카카오톡으로 메시지 전송
     */
	public static void goKaKao(Context context){
    	try { 
	        ArrayList< Map < String, String > > arrMetaInfo = new ArrayList< Map< String, String > >();

	        // If application is support Android platform. 
	        Map < String, String > metaInfoAndroid = new Hashtable < String, String >(1);
	        metaInfoAndroid.put("os", "android");
	        metaInfoAndroid.put("devicetype", "phone");
	        metaInfoAndroid.put("installurl", strInstallUrl);
	        metaInfoAndroid.put("executeurl", strInstallUrl);
	        arrMetaInfo.add(metaInfoAndroid);

	        // If application is support ios platform. 
	        Map < String, String > metaInfoIOS = new Hashtable < String, String >(1);
	        metaInfoIOS.put("os", "ios");
	        metaInfoIOS.put("devicetype", "phone");
	        metaInfoIOS.put("installurl", "pass");
	        metaInfoIOS.put("executeurl", "kakaoLinkTest://starActivity");
	        arrMetaInfo.add(metaInfoIOS);
	        LottoAdKakao link = new LottoAdKakao(context, strURL, strAppId, strAppVer, strMessage, strAppName, arrMetaInfo, "UTF-8");

	        if( link.isAvailable() ) {
	        	context.startActivity(link.getIntent());
	        }
		} catch (Exception e) {
		        e.printStackTrace();
		}
    }
	
	/**
	 * 어플리케이션 버전 코드
	 */
	public static int getAppVersionCode(Context context) {
		int result = 1;
		
		try {
			PackageManager manager = context.getPackageManager();
			PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
			
			result = info.versionCode;
			
		} catch (NameNotFoundException e) {
			result = 1;
		}
		
		return result;
	}
	
	/**
	 * 어플리케이션 버전네임
	 */
	public static String getAppVersionName(Context context) {
		String result = "";
		
		try {
			PackageManager manager = context.getPackageManager();
			PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
			
			result = info.versionName;
			
		} catch (NameNotFoundException e) {
			result = "1.0.0";
		}
		
		return result;
	}
}
